package com.inventive.jmscache.server.hazelcast;

import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.IList;
import com.inventive.jmscache.server.BackendCache;
import com.inventive.jmscache.server.BackendTopic;
import com.inventive.jmscache.server.JmsCacheMessage;
import com.inventive.jmscache.server.BackendQueue;

import javax.transaction.xa.XAResource;
import java.util.ArrayList;
import java.util.List;

/**
 */
public class HazelcastJmsCacheServer implements BackendCache {

    private HazelcastInstance instance = null;

    public void start() {
        instance = Hazelcast.newHazelcastInstance(null);
    }

    public void stop() {
        instance.shutdown();
    }

    public BackendQueue getQueue(String name) {

        return new HazelcastCachedQueue(name);
    }

    public BackendTopic getTopic(String name) {

        return new HazelcastCachedTopic(name);
    }

    public void startTransaction() {
        Hazelcast.getTransaction().begin();
    }

    public void commitTransaction() {
        Hazelcast.getTransaction().commit();
    }

    public void rollbackTransaction() {
        Hazelcast.getTransaction().rollback();
    }

    public List<JmsCacheMessage> getMessages(String queueName, String messageSelector) {
        return new ArrayList<JmsCacheMessage>();
    }

    public List<String> getSubscriptionsForTopic(String name) {
        IList<String> subscriptionIds = Hazelcast.getList(name);
        return new ArrayList<String>(subscriptionIds);
    }

    public void addMessageIdToSubscription(String subscriptionId, String messageId) {
        Hazelcast.getQueue(subscriptionId).add(messageId);
    }

    public XAResource getXAResource() {
        return null;
    }
}
